Skip to main content

Be consistent in use of Numbers

If the engine is able to correctly predict you're using a specific small type for your values, it will be able to optimize the executed code.

In this example, we'll use this trivial function summing the elements of an array and outputting the time it took:

// summing properties
var sum = (function(arr){
var start = process.hrtime();
var sum = 0;
for (var i=0; i<arr.length; i++) {
sum += arr[i];
}
var diffSum = process.hrtime(start);
console.log(`Summing took ${diffSum[0] * 1e9 + diffSum[1]} nanoseconds`); return sum;
})(arr);

Let's make an array and sum the elements:

var N = 12345, arr = [];
for (var i=0; i<N; i++) arr[i] = Math.random();

Result:

 Summing took 384416 nanoseconds

Now, let's do the same but with only integers:

var N = 12345, arr = [];
for (var i=0; i<N; i++) arr[i] = Math.round(1000*Math.random());

Result:

 Summing took 180520 nanoseconds

Summing integers took half the time here.

Engines don't use the same types you have in JavaScript. As you probably know, all numbers in JavaScript are IEEE754 double precision floating point numbers, there's no specific available representation for integers. But engines, when they can predict you only use integers, can use a more compact and faster to use representation, for example, short integers.

This kind of optimization is especially important for computation or data intensive applications.